<template>
  <div style="overflow: auto;">
    <el-form ref="personForm" :rules="rulesForm" :model="personForm" class="formPublic">
      <div class="personLeft">
        <header class="theheader">账号管理</header>
        <img class="leftImg" v-if="personForm.headPortrait.length>0" :src="$store.state.apiUrl+'file/'+personForm.headPortrait[0]" alt="">
        <img class="leftImg" v-else src="../../static/img/nopersonHead.jpg" alt="">
        <span class="lefthr" /><span class="leftSpan">账号信息</span>
      </div>
      <div class="personRight">
          <el-form-item prop="headPortrait" label="用户头像:" >
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="(file)=>{return beforeAvatarUpload(file)}"
            >
              <div class="imagehua" v-for="(item,index) of personForm.headPortrait" :key="index">
                <img :src="$store.state.apiUrl+'file/'+item" class="avatar" />
                <div @click.stop class="imghua">
                  <i @click.stop="resertImg(index)" class="el-icon-delete"></i>
                </div>
              </div>
              <i
                v-show="personForm.headPortrait.length<1"
                class="el-icon-plus avatar-uploader-icon imagehuaican"
              ></i>
            </el-upload>
          </el-form-item>

        <el-form-item prop="accountNumber" label="账号:">
          <span>{{ personForm.accountNumber }}</span>
          <el-button class="personButton" @click="passClick">修改密码</el-button>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称:">
          <el-input
            v-model="personForm.nickname"
            class="dialoginput"
            placeholder="请输入昵称"
            auto-complete="off"
            style="width:216px"
          />
        </el-form-item>
      <!--  <el-form-item label="姓名:" prop="fullName">
          <el-input
            v-model="personForm.fullName"
            class="dialoginput"
            placeholder="请输入姓名"
            auto-complete="off"
            style="width:216px"
          />
        </el-form-item>-->
        <el-form-item prop="phone" label="手机号码:">
          <el-input
            v-model="personForm.phone"
            class="dialoginput"
            placeholder="请输入手机号码"
            auto-complete="off"
            style="width:216px"
          />
       <!--   <el-button class="personButton">修改绑定</el-button>-->
        </el-form-item>
        <el-form-item label="简介:" prop="briefIntroduction">
          <el-input v-model="personForm.briefIntroduction" :autosize="{ minRows: 2, maxRows:6}" type="textarea" placeholder="请输入简介" style="width:216px" />
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button type="primary" @click="setForm">保存</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </div>
    <el-dialog
      title="修改密码"
      :visible.sync="passwordVisible"
      width="430px"
      :inline="true"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :before-close="cancelPassword"
      class="dialogPublic"
    >
      <el-form  ref="passwordForm" :model="passwordForm"  :rules="rulesPass"  class="formPublicPass" >
        <el-form-item prop="oldPass" label="旧密码:">
          <el-input
            v-model="passwordForm.oldPass"
            class="dialoginput"
            placeholder="请输入旧密码"
            auto-complete="off"
            style="width:216px"
          />
        </el-form-item>
        <el-form-item label="新密码:" prop="newPass">
          <el-input
            v-model="passwordForm.newPass"
            class="dialoginput"
            type="password"
            placeholder="请输入新密码"
            auto-complete="off"
            style="width:216px"
          />
        </el-form-item>
        <el-form-item prop="againPass" label="再次输入新密码:">
          <el-input
            v-model="passwordForm.againPass"
            class="dialoginput"
            type="password"
            placeholder="请再次输入新密码"
            auto-complete="off"
            style="width:216px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="passwordSave">保存</el-button>
        <el-button @click="cancelPassword">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import { handlePassword ,userSave,uploadFile} from '@/api/article'
export default {
  name: 'PersonalInfo',
  components: {},
  props: {
    person: {
      type: Object
    }
  },
  data() {
    return {
      /* 个人信息*/
      personForm: {
        id: '',
        headPortrait: [], // 头像
        accountNumber: '', // 账号
        nickname: '', // 昵称
        fullName: '', // 姓名
        phone: '', // 手机号码
        briefIntroduction: ''// 简介
      },
      rulesForm: {
        headPortrait:[
          {required: true, message: '请上传用户头像', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请填写手机号码', trigger: 'blur'},
          {validator:this.validPhone, trigger: 'blur'}
        ],
      },
      /* 修改密码*/
      passwordVisible: false,
      passwordForm: {
        oldPass: '', // 旧密码
        newPass: '', // 新密码
        againPass: ''// 再次确认密码
      },
      rulesPass: {
        oldPass: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPass: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
           { validator: this.passYan, trigger: 'blur' }
        ],
        againPass: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: this.valideRePassword, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    console.log(111,this.person)
    this.personForm= {
        id: this.person.id,
        headPortrait: this.person.headPortrait, // 头像
        accountNumber:  this.person.accountNumber, // 账号
        nickname: this.person.nickname , // 昵称
        phone: this.person.phone , // 手机号码
        briefIntroduction:  this.person.briefIntroduction// 简介
    }
  },
  methods: {
    async logout() {
    await this.$store.dispatch('user/logout')
    this.$router.push(`/login?redirect=${this.$route.fullPath}`)
   },
    /** ******************设置个人信息******************/
    // 保存个人信息
    setForm() {
    this.$refs['personForm'].validate((valid) => {
      if (valid) {
        userSave({
          id: this.personForm.id,
          iocn: this.personForm.headPortrait.join(','), // 头像
          account:  this.personForm.accountNumber, // 账号
          name: this.personForm.nickname , // 昵称
          phone: this.personForm.phone , // 手机号码
          sex:'',//性别
          remark:  this.personForm.briefIntroduction// 简介
        }).then(res => {
          if(res.code==1){
          this.logout();
        }
      })
      }
    })
    },
    // 取消
    cancelForm() {
      this.$emit('fanhui')
    },
    /********************上传**********************/
    //上传图片
    handleAvatarSuccess(file) {
      this.personForm.headPortrait = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
     if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG格式或者PNG格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return;
      }
    if(file){
      let fileData = new FormData()
      fileData.append('file',file)
       uploadFile(fileData).then(res => {
            if (res.code == 1) {
              const fileImg = res.data.url
              this.personForm.headPortrait.push(fileImg)
            } else {
              this.$message({
                type: 'error',
                message: '图片上传失败'
              })
            }
        })
    }
      return false
    },
    resertImg(index) {
      this.personForm.headPortrait.splice(index, 1)
    },
    /********************上传结束**********************/
    /** ******************设置个人信息结束******************/

    /** ******************修改密码******************/
    // 弹出
    passClick() {
      this.passwordVisible = true
      this.passwordForm={
        oldPass: this.personForm.password, // 旧密码
        newPass: '', // 新密码
        againPass: ''// 再次确认密码
      }
    },
    // 保存
    passwordSave() {
        this.$refs.passwordForm.validate(valid => {
           if(valid){
               handlePassword({
                    password:this.passwordForm.oldPass,
                    newPassword:this.passwordForm.newPass
                  }).then(res=>{
                    if(res.code==1){
                      this.$message({
                        type:'success',
                        message:'修改密码成功'
                      })
                    this.logout()
                   }
                  })
               }
        })
    },
    // 取消
    cancelPassword() {
      this.passwordVisible = false
      this.$refs.passwordForm.resetFields()
      this.$refs.passwordForm.clearValidate()
    },
    /** ******************修改密码结束******************/
    /** ******************校验******************/
    passYan(rule, value, callback) {
      // const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
     const reg=/^[A-Za-z0-9]{6,12}$/
      if (!reg.test(value)) {
        callback(new Error('请输入6-12位密码'))
      } else {
        callback()
      }
    },
    valideRePassword(rule, value, callback) {
      if (value !== this.passwordForm.newPass) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    },
      validPhone(rule, value, callback) {
    var re = /^1[0-9]{10}$/;
    if (value && !re.test(value)) {
      callback(new Error('请输入正确格式的手机号'));
    } else {
      callback();
    }
  },
  }
}
</script>
<style>
  .formPublicPass .el-form-item--medium .el-form-item__label{
    width: 150px;
  }
 .personRight .avatar-uploader .el-upload{
    border-radius:50% ;

 }
</style>
<style  scoped lang="scss">
  .components-container {
    position: absolute;
    top: 0;
    left: 0;
    margin:0px 22px;
    padding: 10px 80px;
    width: 100%;
    height:100% ;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  /*header*/
  .theheader{
    line-height: 40px;
    text-align: left;
    width: 100%;
    height: 40px;
    font-weight: bold;
    font-size: 16px;
    font-family: 萍方-简;
    color:#000;
  }

  /**/
  .formPublic {
    display: flex;
    padding: 23px 20%;
    margin: 0px 0px 20px 0px;
    .personLeft{
      box-shadow:2px 2px 3px #aaaaaa;
      width:20%;display: inline-block;border:1px solid rgba(236,236,236,1);margin-right: 10px;padding-left:20px;
      &:hover{
        box-shadow:2px 2px 3px #aaaaaa;
      }
      .leftImg{
        width: 78px;
        height: 78px;
        display: block;
        margin-bottom: 20px;
      }
      .lefthr{
        height: 15px;
        border-right: 2px solid rgba(44,153,236,1);
        margin: 4px 11px 0px 0px;
      }
      .leftSpan{
        width:28px;
        height:20px;
        font-size:15px;
        font-family:PingFang SC;
        font-weight:400;
        color:rgba(44,153,236,1);
        line-height:20px;
      }
    }
    .personRight{
      width:78%;display: inline-block;border:1px solid rgba(236,236,236,1);
      box-shadow:2px 2px 3px #aaaaaa;
      .personButton{
        border: 0;
        font-family:PingFang SC;
        font-weight:400;
        color:rgba(44,153,236,1);
        cursor: pointer;
      }
    }
  }
</style>

